<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	private function _getWeibo(){
		$weiboService=new SinaWeibo(Yii::app()->params['weibo']['key'], Yii::app()->params['weibo']['secret']);
		return $weiboService;
	}

	private function _getWeiboClient(){
		if($_SESSION['weibo_token']){
			$weiboClient = new SaeTClientV2(
				Yii::app()->params['weibo']['key'], 
				Yii::app()->params['weibo']['secret'], 
				$_SESSION['weibo_token']['access_token']
			);
			return $weiboClient;
		}
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		$weiboService=$this->_getWeibo();
		$weibo_url = $weiboService->getAuthorizeURL( Yii::app()->params['weibo']['callback'] );

		$arrTplData['weibo_url'] = $weibo_url;

		$this->renderFile('index.tpl', $arrTplData);
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	var_dump($error);
	    	/*
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	         */
	    }
	}


	public function actionWeiboCallback()
	{
		$weiboService = $this->_getWeibo();
		if (isset($_REQUEST['code'])) {
			$keys = array();
			$keys['code'] = $_REQUEST['code'];
			$keys['redirect_uri'] = Yii::app()->params['weibo']['callback'];
			try {
				$token = $weiboService->getAccessToken( 'code', $keys ) ;
			} catch (OAuthException $e) {
			}
		}
		
		if ($token) {
			$_SESSION['weibo_token'] = $token;
			//与jssdk cookie 互动
			setcookie( 'weibojs_'.$weiboService->client_id, http_build_query($token) );

			$modelUser = new User();
			$user = $modelUser->getUser(array('weibo_id' => $token['uid']));
			if(! $user){
				$weiboClient = $this->_getWeiboClient();
				$weiboUser = $weiboClient->show_user_by_id($token['uid']);
				$user = array();
				$user['weibo_id'] = $token['uid'];
				$user['username'] = $weiboUser['screen_name'];
				$user['nick'] = $weiboUser['screen_name'];
				$user['gender'] = $weiboUser['gender'];
				$user['reg_time'] = TimeUtil::now();
				$user['login_time'] = TimeUtil::now();
				$modelUser->save($user);
				$user = $modelUser->getUser(array('weibo_id' => $token['uid']));
			}

			$_SESSION['user'] = $user;

			Yii::app()->request->redirect('/user/index');
			#var_dump($token);
			#echo "<h1>成功登录</h1>";
			#exit;
			
		} else {
		    echo '认证失败';
		}
	}




	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	public function actionLogin()
    {
        if (Yii::app()->request->getIsPostRequest())
        {
            
            $input = array(
                'username'   => Yii::app()->request->getPost('username'),
                'password' => Yii::app()->request->getPost('password'),
                'rememberMe' => Yii::app()->request->getPost('password'),
            );

            $modelUser = new User();
			$user=$modelUser->getUser($input);
			$passwd=$modelUser->userPasswdEncrypt($input['password'],$user['reg_time']);
			if($passwd == $user["password"])
			{
				Yii::app()->session['user'] = $user;
				
				Yii::app()->request->redirect(Yii::app()->createURL('pk/pk'));
			}
            else
            {
                Yii::app()->user->setFlash('error','验证失败');
                $this->renderFile('login.tpl');
                exit();
            }
        }
        $this->renderFile('login.tpl');
    }

    public function actionRegister()
    {
    	if (Yii::app()->request->getIsPostRequest())
        {
            
            $input = array(
                'username'   => Yii::app()->request->getPost('username'),
                'password' => Yii::app()->request->getPost('password'),
                'rememberMe' => Yii::app()->request->getPost('password'),
            );

            $modelUser = new User();
			$user=$modelUser->getUser($input);
			$passwd=$modelUser->userPasswdEncrypt($input['password'],$user['reg_time']);
			if($passwd == $user["password"])
			{
				Yii::app()->session['user'] = $user;
				
				Yii::app()->request->redirect(Yii::app()->createURL('pk/pk'));
			}
            else
            {
                Yii::app()->user->setFlash('error','验证失败');
                $this->renderFile('login.tpl');
                exit();
            }
        }
        $this->renderFile('register.tpl');
    }

	
	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
}